package com.hpe.service.Impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpe.dao.BigQuestionMapper;
import com.hpe.dao.CourseMapper;
import com.hpe.pojo.BigQuestion;
import com.hpe.pojo.Course;
import com.hpe.service.BigQuestionService;
import com.hpe.util.DownloadUtil;
import com.hpe.util.ExcelUtil;
import com.hpe.util.ServerResponse;
import com.hpe.vo.BigQuestionVo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:TangWenhao
 * @Description:
 * @Date:19:29 2017/9/25
 */
@Service
public class BigQuestionServiceImpl implements BigQuestionService {

    @Autowired
    BigQuestionMapper bigQuestionMapper;
    @Autowired
    CourseMapper courseMapper;

    @Override
    public ServerResponse<PageInfo> showAllBigQuestions(String bqquestionTitle , String bqcourseName, int  pageNum, int pageSize) {
        //获取分页信息
        PageHelper.startPage(pageNum, pageSize);
        //获取需要显示的所有试题
        List<BigQuestionVo> bigQuestions = bigQuestionMapper.showAllBigQuestions(bqcourseName,bqquestionTitle);
        //分页
        PageInfo pageInfo = new PageInfo(bigQuestions);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<Map<String, Object>> editBigQuestion(BigQuestion bigQuestion) {
        Map<String, Object> returnMap = new HashMap<>();
        BigQuestion returnQuestion;
        returnQuestion = bigQuestionMapper.selectByPrimaryKey(bigQuestion.getId());
        returnMap.put("bigQuestion", returnQuestion);
        List<Course> allCourse = courseMapper.getAllCourseOrderById();
        //获取所有的课程信息
        returnMap.put("allCourse", allCourse);
        if (returnQuestion == null) {
            //添加
            return ServerResponse.createBySuccess("添加", returnMap);
        }
        return ServerResponse.createBySuccess("修改", returnMap);
    }

    @Override
    public ServerResponse updateBigQuestion(BigQuestion bigQuestion) {
        while (true) {
            String str1 = bigQuestion.getTitle().replaceAll("&nbsp;", " ");
            String str2 = bigQuestion.getContentans().replaceAll("&nbsp;", " ");
            if (!str1.contains("&nbsp;") && !str2.contains("&nbsp;")) {
                bigQuestion.setContentans(str2);
                bigQuestion.setTitle(str1);
                break;
            }
        }
        //判断是修改还是添加,如果id为空则是添加
        if (bigQuestion.getId() == null) {
            //传过来的question的类型为Null,exist为null
            bigQuestion.setSpare("1");
            bigQuestionMapper.insert(bigQuestion);
            return ServerResponse.createBySuccess("添加成功");
        } else {
            bigQuestionMapper.updateByPrimaryKeySelective(bigQuestion);
            return ServerResponse.createBySuccess("修改成功");
        }
    }

    @Override
    public ServerResponse deleteBigQuestion(BigQuestion bigQuestion) {
        bigQuestion.setSpare("0");
        bigQuestionMapper.updateByPrimaryKeySelective(bigQuestion);
        return ServerResponse.createBySuccess("删除成功");
    }

    @Override
    public List<BigQuestion> findBigQuesByIds(String[] ids, int type) {
        //String idss= ToolUtil.arraytoString(ids);
        List<BigQuestion> list = new ArrayList<>();
        for (String id : ids) {
            if (id.equals("")) {
                continue;
            }
            //去除富文本编辑器添加的段首与段尾的<p>标签
            BigQuestion bigQuestion = bigQuestionMapper.findBigQuesByIds(Integer.valueOf(id), type);
            int index = bigQuestion.getTitle().indexOf("<p>");
            int index1 = bigQuestion.getContentans().indexOf("<p>");
            if (index == 0) {
                bigQuestion.setTitle(bigQuestion.getTitle().substring(3, bigQuestion.getTitle().length() - 4));
            }
            if (index1 == 0) {
                bigQuestion.setContentans(bigQuestion.getContentans().substring(3, bigQuestion.getContentans().length() - 4));
            }
            //对大题重新赋值。
            list.add(bigQuestion);
        }
        return list;
    }

    @Override
    public ServerResponse loadinExcelForBq(InputStream inputStream, Integer courseId, Integer queType) throws Exception {
        ExcelUtil excelUtil = new ExcelUtil(inputStream, "2007");
        String[] propertyNames = {"Title", "Contentans"};
        Class<?>[] propertyTypes = {String.class, String.class};
        List<BigQuestion> bigQuestions = null;
        try {
            bigQuestions = excelUtil.readExcel(propertyNames, propertyTypes, BigQuestion.class);
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg("您导入的excel有纯数字,请在前边加一个英文单引号或者给他后边加个空格");
        }
        for (BigQuestion bq : bigQuestions) {
            bq.setSpare("1");
            bq.setCourseid(courseId);
            bq.setType(queType);
            bq.setTitle(bq.getTitle());
            bq.setContentans(bq.getContentans());
            bigQuestionMapper.insert(bq);
        }
        return ServerResponse.createBySuccessMsg("导入成功");
    }

    @Override
    public void outputSelectBQuestionExcelTitle(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String[] title = {"题干", "答案"};
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("sheet1");
        XSSFRow row = sheet.createRow(0);
        XSSFCellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 10);
        style.setLocked(true);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setDataFormat(workbook.createDataFormat().getFormat("@"));
        style.setAlignment(HorizontalAlignment.CENTER);
        //添加单元格注释
        //创建HSSFPatriarch对象,HSSFPatriarch是所有注释的容器.
        XSSFDrawing patr = sheet.createDrawingPatriarch();
        //定义注释的大小和位置,详见文档
        XSSFComment comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
        //设置注释内容
        comment.setString(new XSSFRichTextString("注意，请在纯数字前加入英文单引号[']"));

        for (int i = 0; i < title.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[i]);
            cell.setCellComment(comment);
            cell.setCellType(CellType.STRING);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        workbook.close();
        new DownloadUtil().download(os, resp, req, "大题表头.xlsx");
    }

    @Override
    public BigQuestion getBQById(int bqId) {
        return bigQuestionMapper.selectByPrimaryKey(bqId);
    }
}
